package com.qs.home.ui.VM;

import android.app.Application;
import android.databinding.ObservableBoolean;
import android.databinding.ObservableField;
import android.databinding.ObservableInt;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.ImageView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.qs.base.global.SPKeyGlobal;
import com.qs.base.router.RouterActivityPath;
import com.qs.base.utils.PhotoImgUtil;
import com.qs.base.utils.RetrofitClient;
import com.qs.base.utils.TranslateLanguageUtil;
import com.qs.home.R;
import com.qs.home.entity.IdCardFrontResultEntity;
import com.qs.home.entity.TextResultEntity;
import com.qs.home.entity.TranslateEntity;
import com.qs.home.service.ApiService;
import com.qs.home.translate.TranslateClient;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.bus.RxSubscriptions;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 识别结果详情vm
 *
 * @Author ltzz
 * @Date 2019/8/20
 */
public class IdentifyDetailsViewModel extends BaseViewModel {
    public IdentifyDetailsViewModel(@NonNull Application application) {
        super(application);
    }

    //识别数据
    public ObservableField<TextResultEntity> textResultOb = new ObservableField<>();
    //识别详细文字
    public ObservableField<String> textResultStr = new ObservableField<>("");
    //识别详细文字历史
    public String oldTextResultStr = "";
    //识别语种
    public String resultLanguage = "en";
    //识别语种显示
    public ObservableField<String> languageStr = new ObservableField<>("英语");
    //文字是否编辑
    public ObservableInt textHind = new ObservableInt(View.GONE);
    //底部是否编辑
    public ObservableInt botHind = new ObservableInt(View.VISIBLE);

    //身份证识别是否可编辑
    public ObservableBoolean isFocusable = new ObservableBoolean(false);
    //身份证数据
    public ObservableField<IdCardFrontResultEntity> idCardFrontResult = new ObservableField<>();
    //身份证历史数据
    public ObservableField<IdCardFrontResultEntity> oldIdCardFrontResult = new ObservableField<>();
    //身份证文本
    public String idCardText;

    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();

    public class UIChangeObservable {
        //复制文本
        public ObservableBoolean copyTextUc = new ObservableBoolean(false);
        //翻译
        public ObservableBoolean translateUc = new ObservableBoolean(false);
        //翻译导出按钮
        public ObservableBoolean exportUc = new ObservableBoolean(false);
    }


    //返回按钮
    public BindingCommand backClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            finish();
        }
    });

    //保存按钮
    public BindingCommand saveClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            File file = new File(textResultOb.get().getFilePath());
            PhotoImgUtil.saveBitmap(getApplication(), PhotoImgUtil.pathToBitmap(textResultOb.get().getFilePath()), "image");
            ToastUtils.showShort("已保存至相册");
        }
    });

    //复制文本
    public BindingCommand textClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.copyTextUc.set(!uc.copyTextUc.get());
        }
    });
    //修改校对
    public BindingCommand modificationClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            oldTextResultStr = textResultStr.get();
            textHind.set(View.VISIBLE);
            botHind.set(View.INVISIBLE);
        }
    });
    //取消
    public BindingCommand textCloseClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            textResultStr.set(oldTextResultStr);
            textHind.set(View.GONE);
            botHind.set(View.VISIBLE);
        }
    });
    //文字修改保存
    public BindingCommand textSaveClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            textHind.set(View.GONE);
            botHind.set(View.VISIBLE);
        }
    });
    //文字翻译按钮点击
    public BindingCommand textTranslateClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.translateUc.set(!uc.translateUc.get());
        }
    });
    //翻译导出按钮
    public BindingCommand exportClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.exportUc.set(!uc.exportUc.get());
        }
    });
    //身份证文本复制
    public BindingCommand idCardTextClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            idCardText = "姓名：\n" + (idCardFrontResult.get().getName() == null ? "" : idCardFrontResult.get().getName()) +
                    "\n性别：\n" + (idCardFrontResult.get().getGender() == null ? "" : idCardFrontResult.get().getGender()) +
                    "\n民族：\n" + (idCardFrontResult.get().getEthnic() == null ? "" : idCardFrontResult.get().getEthnic()) +
                    "\n出生：\n" + (idCardFrontResult.get().getBirthday() == null ? "" : idCardFrontResult.get().getBirthday()) +
                    "\n住址：\n" + (idCardFrontResult.get().getAddress() == null ? "" : idCardFrontResult.get().getAddress()) +
                    "\n身份证号码：\n" + (idCardFrontResult.get().getIdNumber() == null ? "" : idCardFrontResult.get().getIdNumber()) +
                    "\n签发机关：\n" + (idCardFrontResult.get().getIssueAuthority() == null ? "" : idCardFrontResult.get().getIssueAuthority()) +
                    "\n有效期限：\n" + (idCardFrontResult.get().getSignDate() == null ? "" : idCardFrontResult.get().getSignDate()) + " - " + (idCardFrontResult.get().getExpiryDate() == null ? "" : idCardFrontResult.get().getExpiryDate());
            uc.copyTextUc.set(!uc.copyTextUc.get());
        }
    });

    //身份证修改校对
    public BindingCommand idCardModificationClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            oldIdCardFrontResult.set(idCardFrontResult.get());
            isFocusable.set(!isFocusable.get());
            textHind.set(View.VISIBLE);
            botHind.set(View.INVISIBLE);
        }
    });
    //身份证修改保存
    public BindingCommand idCardTextSaveClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            isFocusable.set(!isFocusable.get());
            textHind.set(View.GONE);
            botHind.set(View.VISIBLE);
        }
    });
    //取消
    public BindingCommand idCardTextTextCloseClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            idCardFrontResult.set(oldIdCardFrontResult.get());
            isFocusable.set(!isFocusable.get());
            textHind.set(View.GONE);
            botHind.set(View.VISIBLE);
        }
    });

    private Disposable subscribe;
    //语言选择
    public BindingCommand selectLanguageClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (subscribe != null && !subscribe.isDisposed())
                subscribe.dispose();
            subscribe = RxBus.getDefault().toObservable(String.class)
                    .subscribe(new Consumer<String>() {
                        @Override
                        public void accept(String result) throws Exception {
                            if (!StringUtils.isTrimEmpty(result))
                                languageStr.set(result);
                            if (subscribe != null && !subscribe.isDisposed())
                                subscribe.dispose();
                        }
                    });
            RxSubscriptions.add(subscribe);
            ARouter.getInstance().build(RouterActivityPath.Home.SELECT_LANGUAGE).withString("language", languageStr.get()).navigation();
        }
    });
    //翻译按钮
    public BindingCommand translateClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            String userId = SPUtils.getInstance().getString(SPKeyGlobal.USER_ID, "");

            if (StringUtils.isTrimEmpty(userId)) {
                String trNumberStr = SPUtils.getInstance().getString(SPKeyGlobal.TRANSLATE_NUMBER, "0");
                float x = Float.parseFloat(trNumberStr);
                if (x <= 0) {
                    ToastUtils.showShort("翻译次数已用完");
                    return;
                }
                // 翻译
                translate();

            } else {
                //已登录
                getNumbersByUserid(userId);
            }

        }
    });

    /**
     * 翻译
     */
    public void translate(){
        //消费成功
        resultLanguage = TranslateLanguageUtil.languageToSymbol(languageStr.get());
        KLog.d("cccc  e= "+resultLanguage +"  cc= "+oldTextResultStr);
        RetrofitClient.getInstance().create(ApiService.class)
                .translate(TranslateClient.getInstance().getTransApiHost(textResultStr.get().toString() ,"auto",resultLanguage))
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) //请求与View周期同步
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle;
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog("转换中...");
                    }
                })
                .subscribe(new Consumer<TranslateEntity>() {
                    @Override
                    public void accept(TranslateEntity o) throws Exception {
                        dismissDialog();

                        if (o != null && o.getTrans_result() != null) {
                            textResultStr.set(o.getTrans_result().get(0).getDst());
                            //未登录使用本地数据
                            int t = textResultStr.get().getBytes().length;
                            int s = t / 3;

                            float tr = Float.parseFloat(SPUtils.getInstance().getString(SPKeyGlobal.TRANSLATE_NUMBER, "0"));
                            int c = (int) (tr - s);
                            if (c > 0)
                                SPUtils.getInstance().put(SPKeyGlobal.TRANSLATE_NUMBER, c + "");
                            else
                                SPUtils.getInstance().put(SPKeyGlobal.TRANSLATE_NUMBER, "0");
                        }else{
                            ToastUtils.showLong("转换失败..");
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dismissDialog();
//                        ToastUtils.showLong("转换失败..");
                    }
                });
    }

    /**
     * 剩余翻译次数
     *
     * @param userid
     */
    public void getNumbersByUserid(String userid) {

        Map<String, Object> map = new HashMap<>();
        map.put("userid", userid);
        RetrofitClient
                .getInstance()
                .create(ApiService.class)
                .getNumbersByUserid(map)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) //请求与View周期同步
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) {
                        showDialog();
                    }
                })
                .subscribe(new Consumer<Map<String, Object>>() {
                    @Override
                    public void accept(Map<String, Object> baseResult) throws Exception {
                        if (baseResult != null) {
                            String number = baseResult.get("numbers").toString();
                            if (StringUtils.isTrimEmpty(number)) {
                                dismissDialog();
                                ToastUtils.showShort("翻译次数已用完");
                                return;
                            } else {
                                float t = textResultStr.get().getBytes().length;
                                float s = t / 3;
                                if (s > 0) {
                                    //初始化数据
                                    String userId = SPUtils.getInstance().getString(SPKeyGlobal.USER_ID);
                                    if (!StringUtils.isTrimEmpty(userId)) {
                                        //用户已登录使用服务器数据
                                        subNumbers(userId, s + "");
                                    } else {
                                        //未登录使用本地数据
                                        float tr = Float.parseFloat(SPUtils.getInstance().getString(SPKeyGlobal.TRANSLATE_NUMBER, "0"));
                                        float c = tr - s;
                                        if (c > 0)
                                            SPUtils.getInstance().put(SPKeyGlobal.TRANSLATE_NUMBER, c + "");
                                        else
                                            SPUtils.getInstance().put(SPKeyGlobal.TRANSLATE_NUMBER, "0");
                                    }
                                }
                            }
                        } else {
                            dismissDialog();
                        }
                    }

                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //异常
                        dismissDialog();
                        ToastUtils.showLong("翻译剩余字数获取失败..");
                    }
                });
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            dismissDialog();
            if (msg.what == 0) {
                TranslateEntity translate = (TranslateEntity) msg.obj;
                textResultStr.set(translate.getTrans_result().get(0).getDst());
            }
        }
    };

    /**
     * 消费翻译次数
     *
     * @param userId
     * @param number
     */
    public void subNumbers(String userId, String number) {

        Map<String, Object> map = new HashMap<>();
        map.put("userid", userId);
        map.put("wordnumber", number);
        Gson gson = new Gson();
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), gson.toJson(map));
        RetrofitClient
                .getInstance()
                .create(ApiService.class)
                .subNumbers(body)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) //请求与View周期同步
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) {
                        showDialog();
                    }
                })
                .subscribe(new Consumer<Map<String, Object>>() {
                    @Override
                    public void accept(Map<String, Object> baseResult) throws Exception {
                        dismissDialog();
                        if (baseResult != null && Double.parseDouble(baseResult.get("code") + "") == 0) {
                            //消费成功
                            resultLanguage = TranslateLanguageUtil.languageToSymbol(languageStr.get());
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    String result = TranslateClient.getInstance().getTransResult(textResultStr.get(), "auto", resultLanguage);
                                    try {
                                        Gson gson = new Gson();
                                        TranslateEntity translate = gson.fromJson(result, TranslateEntity.class);
                                        Message message = new Message();
                                        message.obj = translate;
                                        message.what = 0;
                                        handler.sendMessage(message);
                                    } catch (Exception e) {
                                        Message message = new Message();
                                        message.what = 1;
                                        handler.sendMessage(message);
                                    }
                                }
                            }).start();
                        } else {
                            ToastUtils.showShort("剩余次数不足..");
                        }
                    }

                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //异常
                        //模拟成功
                        dismissDialog();
                    }
                });

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (subscribe != null && !subscribe.isDisposed())
            subscribe.dispose();
    }

    public void loadImage(ImageView imageView, String url) {
        RequestOptions mRequestOptions = new RequestOptions()
                .override(imageView.getWidth(), imageView.getHeight())
                .skipMemoryCache(true) // 不使用内存缓存
                .diskCacheStrategy(DiskCacheStrategy.NONE) // 不使用磁盘缓存
                .error(R.drawable.no_banner);
        Glide.with(imageView.getContext())
                .load(url)
                .apply(mRequestOptions)
                .into(imageView);
    }
}
